package com.deep.test.parallel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 会员等级处理主线程
 * @author hudepin
 *
 * 2017年12月26日下午1:34:54
 */
public class MemberLevelParallelMain {
	public static void main(String[] args) throws InterruptedException {
		MyExecutor executor = new MyExecutor(20, 50, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
		List<Future<List<User>>> futures = new ArrayList<Future<List<User>>>();
		Map<Integer,List<User>> map = new HashMap<Integer,List<User>>();
		// 模拟处理会员等级信息
		List<User> users = genUserList();
		long startTime = System.currentTimeMillis();
		// 一个任务处理100条数据
		int dataLimitSize = 10;
		int size = users.size();
		if (dataLimitSize < size) {
			int part = size / dataLimitSize;
			//System.out.println("共有 ： " + size + "条，！" + " 分为 ：" + part + "批");
			for (int i = 0; i < part; i++) {
				List<User> subUsers = users.subList(i*dataLimitSize, (i+1)*dataLimitSize);
				System.out.println("i:"+i+"memberId:"+subUsers.get(0).getMemberId());
				map.put(i, subUsers);
				futures.add(executor.submit(new MemberLevelCallable(subUsers)));
			}
		}
		// 提交所有的任务后,关闭executor
		System.out.println("Starting shutdown executor...");
		executor.shutdown();
		// 每秒钟打印执行进度
		while (!executor.isTerminated()) {
			executor.awaitTermination(1, TimeUnit.SECONDS);
			int progress = Math.round((executor.getCompletedTaskCount() * 100) / executor.getTaskCount());
			//System.out.println(progress + "% done (" + executor.getCompletedTaskCount() + " users have been process).");
		}
		int errorCount = 0;
		int successCount = 0;
		try {
			for (Future<List<User>> future : futures) {
				//System.out.println("future done,"+future.isDone());
				List<User> list = future.get();
				List<User> users1 = map.get(successCount);
				System.out.println("count:"+successCount+"size"+users1.size()+"memberId:"+users1.get(0).getMemberId());
				if (list != null) {
					successCount++;
				} else {
					errorCount++;
				}
				
			}
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println(successCount + " data successfully process, but " + errorCount + " failed.");
		System.out.println("time:" + (System.currentTimeMillis() - startTime) / 1000 + "s");
	}

	private static List<User> genUserList() {
		List<User> list = new ArrayList<User>(1000);
		long i = 0;
		for (; i < 1000; i++) {
			User u = new User();
			u.setMemberId(i);
			u.setMemberLevel("20");
			list.add(u);
		}
		return list;
	}
}
